
// home/BleHome.js
function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}
// 字符串转byte
function stringToBytes(str) {
    var array = new Uint8Array(str.length);
    for (var i = 0, l = str.length; i < l; i++) {
        array[i] = str.charCodeAt(i);
    }
    console.log(array);
    return array.buffer;
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    IsConnect: false,
    calValue:'0',
    stepValue:'0',
    REQdata:[],
    chs:[],
    name:'',
    deviceId:''
  },

  userInfo:function(){
    wx.navigateTo({
      url: "../useAdmin/useAdmin" 
    })
  },
  realTimeData:function(){
    wx.navigateTo({
      url: "../realTimeData/realTimeData"
    })
  },
  showData:function(){
    wx.navigateTo({
      url: '../showData/showData' 
    })
  },
  physicalData:function(){
    wx.navigateTo({
      url: '../physicalData/physicalData' 
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let _this=this;
    _this.reqData();
    _this.BLEAdapter();
    let deviceId = wx.getStorageSync('DeviceId');
    wx.onBluetoothAdapterStateChange(function(res) {
        if(res.connected){
            // _this.IsConnect();
            _this.setData({
                IsConnect: true,
                deviceId:deviceId,
            });
        }else{
            _this.createBLEConnection(deviceId);
           
        }
    });
  },
  //下拉刷洗
  onPullDownRefresh: function () {
    console.log('onPullDownRefresh')
    let _this=this;
    let deviceId = wx.getStorageSync('DeviceId');
    _this.BLEAdapter();
    wx.onBluetoothAdapterStateChange(function(res) {
        if(res.connected){
            // _this.IsConnect();
            _this.setData({
                IsConnect: true,
                deviceId:deviceId,
            });
            wx.stopPullDownRefresh();
        }else{
            _this.createBLEConnection(deviceId);
            
        }
    });
  },
  onShow:function(){
    let _this=this;
    let deviceId = wx.getStorageSync('DeviceId');
    _this.BLEAdapter();
    wx.onBluetoothAdapterStateChange(function(res) {
        if(res.connected){
            // _this.IsConnect();
            _this.setData({
                IsConnect: true,
                deviceId:deviceId,
            });
        }else{
            _this.createBLEConnection(deviceId);
          
        }
    });
  },
  
  //方法：蓝牙是否可用
  openBluetoothAdapter(){
    let _this=this;
    wx.openBluetoothAdapter({
        success: function (res) {
            console.log('openBluetoothAdapter success', res)
            _this.getBluetoothAdapterState();
        },
        fail(res){
            console.log('openBluetoothAdapter fail', res)
            wx.showModal({
                title: '提示',
                content: '请开启蓝牙设备',
                success: function(res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
            wx.onBluetoothAdapterStateChange(function(res) {
                if(res.available){
                  setTimeout(function(){
                      _this.openBluetoothAdapter()
                  },500);
                }
            });
        }
    });        
},
//方法：蓝牙是否开启
getBluetoothAdapterState(){
    let _this=this;
    wx.getBluetoothAdapterState({
        success: (res) => {
            console.log('getBluetoothAdapterState', res) ;
            _this.BLESeach();//开始搜索
        },
        fail(res) {
            console.log('getBluetoothAdapterState fail', res);
        }
    })  
},
BLEAdapter(){
    // 1.微信小程序：是否支持；
    if(!wx.openBluetoothAdapter){
        wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        });
      return;
    };
    // 2.手机蓝牙：是否可用；// 3.手机蓝牙：是否开启// 4.监听开启手机蓝牙状态的事件
    this.openBluetoothAdapter();
},
  // 方法：开始搜索周围是否有设备；
  startBluetoothDevicesDiscovery() {
    let _this=this;
    wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: (res) => {
            console.log('startBluetoothDevicesDiscovery success', res)
            wx.onBluetoothDeviceFound(res=>{
                let devices = res.devices;
                let mac = wx.getStorageSync('DeviceId');
                wx.stopPullDownRefresh();
                if(!mac){
                    wx.showModal({
                        title: '提示',
                        content: '设备未连接，请连接设备',
                        confirmText: "是",
                        cancelText: "否",
                        success: function (res) {
                            wx.navigateTo({
                                url: '../connectingBluetooth/connectingBluetooth'
                            })
                        }
                    });
                    wx.stopBluetoothDevicesDiscovery({
                      success:res=>console.log(res),
                     fail:res=>console.log(res),
                    })
                    
                }
               
            })
        },
        fail(res) {
            console.log('startBluetoothDevicesDiscovery fail', res)
        }
    })
},

BLESeach(){
   this.startBluetoothDevicesDiscovery();
},
//方法：服务值
getBLEDeviceServices(deviceId){
    let _this=this;
    wx.getBLEDeviceServices({
        deviceId:deviceId,
        success: (res) => {
            for (let i = 0; i < res.services.length; i++) {
                // 注：解析过程出现两个service，第二个是以前使用的，所以这里添加判断
                if (res.services[i].uuid.indexOf("6E400001") != -1) {
                    if (res.services[i].isPrimary) {
                        wx.setStorageSync('ServiceId', res.services[i].uuid);
                        _this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
                        return
                    }
                }
            };
        },
        fail(res) {
            console.log('获取服务码错误：', res)
        }
    });
},
//方法：write和notify服务
getBLEDeviceCharacteristics(deviceId, serviceId) {
    let _this=this;
    wx.getBLEDeviceCharacteristics({
        deviceId:deviceId,
        serviceId:serviceId,
        success: (res) => {
            console.log('getBLEDeviceCharacteristics success', res.characteristics)
            for (let i = 0; i < res.characteristics.length; i++) {
                let item = res.characteristics[i]
        
                if (item.properties.read) {
                    wx.readBLECharacteristicValue({
                        deviceId:deviceId,
                        serviceId:serviceId,
                        characteristicId: item.uuid,
                    })
                }
                if (item.properties.write) {
                    wx.setStorageSync('CharacteristicId', item.uuid);
                    _this.writeBLECharacteristicValue();//先同步
                }
                if (item.properties.notify || item.properties.indicate) {
                    wx.notifyBLECharacteristicValueChange({
                        deviceId:deviceId,
                        serviceId:serviceId,
                        characteristicId: item.uuid,
                        state: true,
                        complete(res) {
                            _this.onBLECharacteristicValueChange();//接受消息
                           
                          }
                    })
                }
            }
        },
        fail(res) {
            console.error('getBLEDeviceCharacteristics', res)
        }
    })
},

  // 同步数据
  upload:function(){
    this.writeBLECharacteristicValue(); 
  },
  reqData:function(){
    let reqDatas = wx.getStorageSync('ReqData');
    this.setData({
        calValue:reqDatas.Calorie,
        stepValue:reqDatas.Step,
        IsConnect:wx.getStorageSync('IsConnect')
    })
  },
  //方法：连接设备
  createBLEConnection(deviceId){
    let _this=this;
    wx.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
            _this.setData({
                IsConnect:true
            });
            console.log('连接成功', res);
            _this.getBLEDeviceServices(deviceId);
            wx.setStorageSync('IsConnect', true);
            wx.stopBluetoothDevicesDiscovery({
                success:res=>console.log(res),
                fail:res=>console.log(res),
            })
        }
    });
},


  //发送：同步指令
  writeBLECharacteristicValue(){
    let _this=this;
    let order="REQDATA";
    let buffer = stringToBytes(order);
    let deviceId = wx.getStorageSync('DeviceId');
    let serviceId = wx.getStorageSync('ServiceId');
    let characteristicId = wx.getStorageSync('CharacteristicId');
    wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: buffer,
        success: function (res) {
            console.log("发送成功", res);
           _this.notifyBLECharacteristicValueChange()//接收消息
        },
        fail(res) {
            wx.showModal({
                title: '提示',
                content: '发送失败'
            });
            console.log("发送失败", res)
        }
    })
}, 
//方法
notifyBLECharacteristicValueChange(){
    let _this=this;
    let deviceId = wx.getStorageSync('DeviceId');
    let serviceId = wx.getStorageSync('ServiceId');
    let characteristicId = wx.getStorageSync('CharacteristicId');
    wx.notifyBLECharacteristicValueChange({
        deviceId:deviceId,
        serviceId:serviceId,
        characteristicId: characteristicId,
        state: true,
        complete(res) {
             
            _this.onBLECharacteristicValueChange();//接受消息
            _this.writeBLECharacteristicValueSTART();
        }
    });
},
 // 开始start
 writeBLECharacteristicValueSTART(){
    let  dtTime= Date.parse(new Date())/1000;//时间戳：秒
    let  order="START"+dtTime;
    let  buffer = stringToBytes(order);
    let deviceId = wx.getStorageSync('DeviceId');
    let serviceId = wx.getStorageSync('ServiceId');
    let characteristicId = wx.getStorageSync('CharacteristicId');
    wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: buffer,
        success: function (res) {
            console.log("开始成功", res)
            wx.stopPullDownRefresh();
        },
        fail(res) {
            console.log("发送失败", res)
        }
    })
},
//方法:接受消息
onBLECharacteristicValueChange(){
    let _this=this;
    wx.onBLECharacteristicValueChange((characteristic) => {
        _this.data.REQdata.push(ab2hex(characteristic.value));
        const idx = inArray(_this.data.chs, 'uuid', characteristic.characteristicId); 
        // console.log('监听同步返回数据',ab2hex(characteristic));
        // console.log('同步单个数据',ab2hex(characteristic.value));
        // console.log('同步数据数组参数', _this.data.REQdata);

        //发送完测量数据后会再发送一个 END 字符串表示发送完毕。
        if (characteristic.value.byteLength == 3){
            wx.request({
              url: 'https://ssldev.imreliable.com:5010/handRing/updataDTing', //接口地址
                data: {
                    HandRingMac: wx.getStorageSync('DeviceId'),
                    DataStreams: this.data.REQdata
                },
                method:'POST',
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success: function(res) {
                    wx.hideLoading();
                    _this.writeBLECharacteristicValueSTART();
                    console.log('后台返回数据',res.data);
                    wx.setStorageSync("ReqData", res.data);
                    _this.reqData();
                    wx.showModal({
                        title: '提示',
                        content: '同步成功'
                    });
                    _this.data.REQdata=[];
                },
                fail: (res) => {
                    console.log(res.data);
                },
            });
            _this.reqData();
            return;
        };
    })
},
 
})